require "easy_form/version"
require 'action_view'
require 'easy_form/action_views/form_helper'
module EasyForm
  extend ActiveSupport::Autoload

  autoload_under 'autoloads' do
    autoload :Helpers
    autoload :Wrappers
  end

  eager_autoload do
    autoload :FormBuilder
    autoload :ErrorNotification

    autoload_under 'autoloads' do
      autoload :Inputs
      autoload :Components
    end
  end

  def eager_load!
    super
    EasyForm::Inputs.eager_load!
    EasyForm::Components.eager_load!
  end

  @@configured = false
  def self.configured?;@@configured;end

  def self.setup
    @@configured = true
    yield self
  end

  mattr_accessor :field_error_proc
  @@field_error_proc = proc {|html_tag, _| html_tag}

  mattr_accessor :default_wrapper
  @@default_wrapper = :default
  @@wrappers = {}

  def self.wrapper(name)
    @@wrappers[name.to_s] or raise "Couldn't find wrapper with name #{name}"
  end

  def self.wrappers(*args, &block)
    return @@wrappers unless block_given?

    options                = args.extract_options!
    name                   = args.first || :default
    @@wrappers[name.to_s]  = wrapper_build(options, &block)
  end

  def self.wrapper_build(options = {})
    options[:tag] ||= :div
    builder = EasyForm::Wrappers::Builder.new(options)
    yield builder

    EasyForm::Wrappers::Root.new(builder.to_a, options)
  end

  #缓存类型，开发环境用请求间缓存
  mattr_accessor :cache_discovery
  @@cache_discovery = defined?(Rails.env) && !Rails.env.development?

  mattr_accessor :wrapper_mappings
  @@wrapper_mappings = nil

  mattr_accessor :generate_additional_classes_for
  @@generate_additional_classes_for = %i[wrapper input label]
  def self.additional_classes_for(component)
    generate_additional_classes_for.include?(component) ? yield : []
  end

  mattr_accessor :input_class
  @@input_class = nil

  mattr_accessor :translate_labels
  @@translate_labels = true

  mattr_accessor :label_text
  @@label_text = ->(label, required, explicit_label) { "#{label} #{required}" }

  mattr_accessor :i18n_scope
  @@i18n_scope = 'easy_form'

  mattr_accessor :required_by_default
  @@required_by_default = true

  mattr_accessor :error_method
  @@error_method = :first

  mattr_accessor :error_notification_tag
  @@error_notification_tag = :p
  mattr_accessor :error_notification_class
  @@error_notification_class = :error_notification

  mattr_accessor :button_class
  @@button_class = nil
  mattr_accessor :label_class
  @@button_class = nil

  require 'easy_form/railtie' if defined?(Rails)
end
